<template>
    <el-row :gutter="20">
        <el-col :span="12">
            <section>
                <h3>已规划路线列表</h3>
                <el-form class="pinmei-form" inline>
                    <el-form-item>
                        <el-select
                            v-model="formData.company"
                            clearable
                            collapse-tags
                            placeholder="请选择主体"
                            class="select"
                        >
                            <template #prefix>
                                <div class="label">选择主体</div>
                            </template>
                            <el-option
                                v-for="(item, index) in grouplist"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            /> </el-select
                        ></el-form-item>
                    <el-form-item>
                        <el-input v-model="formData.name" placeholder="搜索线路名称" clearable class="formname">
                            <template #prefix>
                                <div class="label">
                                    <el-icon :size="16">
                                        <Search />
                                    </el-icon>
                                </div>
                            </template>
                        </el-input>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <el-button type="primary" @click="getRoute"> 查询 </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" plain @click="addRoute"> 添加 </el-button>
                        <el-button type="primary" :loading="exportLoading" plain @click="onExportRoute">
                            导出
                        </el-button>
                    </el-form-item>
                </el-form>
            </section>
            <XcTable
                id="xc-table"
                :loading="tableRouteLoading"
                :data="tableDataRouteList"
                is-selectable
                :columns="tableRouteColumns"
                @selection-change="handleSeletionChange"
                @row-click="rowClick"
            >
                <template #index="scope">
                    {{ scope.$index + 1 }}
                </template>
                <template #name="{ row }">
                    <!-- <el-button type="text" @click="getRoutePremises(row)"> {{ row.name }}</el-button> -->
                    {{ row.name }}
                </template>
                <template #action="{ row }">
                    <el-button type="text" @click.stop="onEdit(row)">编辑</el-button>
                    <el-button type="text" @click.stop="onDelete(row)">删除</el-button>
                    <el-dropdown trigger="click">
                        <span class="el-dropdown-link">
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                viewBox="0 0 1024 1024"
                                class="row-actions__more"
                                color="#4D88FF"
                                data-v-62ab440c=""
                            >
                                <path
                                    fill="currentColor"
                                    d="M176 416a112 112 0 1 1 0 224 112 112 0 0 1 0-224zm336 0a112 112 0 1 1 0 224 112 112 0 0 1 0-224zm336 0a112 112 0 1 1 0 224 112 112 0 0 1 0-224z"
                                />
                            </svg>
                        </span>

                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item>
                                    <el-button type="text" style="color: #252525" plain @click.stop="onAllocate(row)"
                                        >分配账号</el-button
                                    >
                                </el-dropdown-item>
                                <el-dropdown-item>
                                    <el-button
                                        type="text"
                                        style="color: #252525"
                                        plain
                                        @click.stop="getRoutePremises(row)"
                                        >路线项目</el-button
                                    >
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </XcTable>
        </el-col>
        <el-col :span="12">
            <section>
                <h3>尚未设置路线的项目</h3>
                <el-form>
                    <el-form-item>
                        <el-button type="primary" plain :disabled="!premisesList.length" @click="onAddPremises">
                            批量加入
                        </el-button>
                    </el-form-item>
                </el-form>
            </section>
            <XcTable
                id="xc-table"
                :loading="tableNoPremisesLoading"
                is-selectable
                :data="NotAssociatePremisesList"
                :columns="tablePremisesColumns"
                @selection-change="handlePremisesChange"
            >
                <template #index="scope">
                    {{ scope.$index + 1 }}
                </template>
                <template #type="{ row }">
                    {{ permiseTypeList.find((item) => item.code === row.type).name }}
                </template>
            </XcTable>
        </el-col>
    </el-row>

    <el-dialog v-model="dialogVisible" width="386px" title="添加线路" @closed="handleClose">
        <el-form ref="addFormRef" :model="addForm" status-icon label-position="top" :rules="addFormRulesData">
            <el-form-item label="线路名称" prop="name">
                <el-input v-model="addForm.name" size="large" clearable maxlength="20" placeholder="请输入线路名称" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input
                    v-model="addForm.remark"
                    size="large"
                    type="textarea"
                    clearable
                    maxlength="50"
                    placeholder="请输入备注"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button size="large" @click="handleClose">取消</el-button>
                <el-button size="large" type="primary" :loading="btnLoading" @click="onAddRoute">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog v-model="isAllocateDialog" width="435px" title="分配账号" @closed="handleAllocateClose">
        <el-form ref="addFormRef" :model="addForm" status-icon class="pinmei-form" label-position="top">
            <section>
                <el-tabs class="tab-pane common-table-tabs">
                    <el-tab-pane label="分配账号" :name="0">
                        <el-form-item>
                            <el-input v-model="accountKeyword" placeholder="搜索账号" clearable class="formname">
                                <template #prefix>
                                    <div class="label">
                                        <el-icon :size="16">
                                            <Search />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-input>
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            <el-button type="primary" @click="onSearchAccount"> 查询 </el-button>
                        </el-form-item>
                        <section>
                            <el-checkbox-group v-model="checkedAccount">
                                <el-checkbox v-for="item in dataNotAllotAccount" :key="item" :label="item">{{
                                    item
                                }}</el-checkbox>
                            </el-checkbox-group>
                        </section>
                    </el-tab-pane>
                    <el-tab-pane label="已分配账号" :name="1">
                        <section>
                            <span v-for="(item, index) in dataAllotAccount" :key="index" class="itemAccount"
                                >{{ item }} <el-icon @click="onDelAccount(index)"><Close /></el-icon
                            ></span>
                        </section>
                    </el-tab-pane>
                </el-tabs>
            </section>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button size="large" @click="handleAllocateClose">取消</el-button>
                <el-button
                    size="large"
                    type="primary"
                    :disabled="!checkedAccount.length"
                    :loading="btnLoading"
                    @click="onAccountAallot"
                    >确认</el-button
                >
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogRouteVisible" width="386px" title="更改路线" @closed="handleRouteClose">
        <el-form ref="addFormRef" :model="addForm" status-icon label-position="top">
            <el-form-item label="线路名称" prop="name">
                <el-select v-model="changeRouteId" clearable collapse-tags placeholder="请选择线路">
                    <el-option
                        v-for="(item, index) in tableDataRouteList"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                        :disabled="item.id === currentRouteId"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button size="large" @click="handleRouteClose">取消</el-button>
                <el-button size="large" type="primary" :loading="btnLoading" @click="onRouteChange">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <el-drawer
        :title="currentRouteName ? currentRouteName : '路线项目'"
        :model-value="modelValue"
        :size="860"
        @closed="modelValue = false"
    >
        <section>
            <el-form>
                <el-form-item>
                    <el-button
                        type="primary"
                        plain
                        :disabled="!routePremisesSelection.length"
                        @click="dialogRouteVisible = true"
                    >
                        更换路线
                    </el-button>
                    <el-button
                        type="primary"
                        plain
                        :disabled="!routePremisesSelection.length"
                        @click="onRouteBatchRemove"
                    >
                        批量移除
                    </el-button>
                </el-form-item>
            </el-form>
        </section>
        <XcTable
            id="xc-table"
            :loading="tablePremisesLoading"
            is-selectable
            :data="tablePremisesData"
            :columns="tableSetRouteColumns"
            @selection-change="handleRouteChange"
        >
            <template #index="scope">
                {{ scope.$index + 1 }}
            </template>
            <template #type="{ row }">
                {{ permiseTypeList.find((item) => item.code === row.type).name }}
            </template>
            <template #action="{ row }">
                <el-button type="text" @click="onRemovePremises(row)">移除</el-button>
            </template>
        </XcTable>
    </el-drawer>
    <TipsDailog
        title="提示"
        content="你确认要删除吗？"
        :dialog-visible="dialogDelVisible"
        @onClose="dialogDelVisible = false"
    >
        <el-button @click="dialogDelVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="confirmHanle"> 确认 </el-button>
    </TipsDailog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';
import { addFormRules } from './rules.ts';
import TipsDailog from '@/components/TipsDailog.vue';
import { exportFormBlob, validateForm } from '@/utils/common';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import {
    exportRouteList,
    getRouteList,
    saveRoute,
    updateRoute,
    deleteRoute,
    findPremisesByRouteId,
    findNotAssociatePremises,
    addPremisesToRoute,
    removePremisesFromRoute,
    changeRouteOfPremises,
    getNotAllotAccountList,
    getAllotAccountList,
    allotAccount,
} from '@/api/route';
import { fa } from 'element-plus/lib/locale/index';

// 加盟商编码（登录时已保存）
const addFormRef = ref<FormInstance>();
const addFormRulesData = reactive<FormRules>(addFormRules);
const store = useStore();
const userGroup = computed(() => store.state.userGroup);
const permiseTypeList = computed(() => store.state.app.common.CommonList.permiseList);
const grouplist = ref([]);
const exportLoading = ref(false);
const tableDataRouteList = ref([]);
const NotAssociatePremisesList = ref([]);
const multipleRouteSelection = ref([]);
const dataAllotAccount = ref([]);
const dataNotAllotAccount = ref([]);
const tablePremisesData = ref([]);
const changeRouteId = ref('');
const formData = reactive({ company: '', name: '' });
const dialogVisible = ref(false);
const isAllocateDialog = ref(false);
const addForm = reactive({ id: '', name: '', remark: '', company: '' });
const currentId = ref('');
const currentRouteId = ref('');
const currentRouteName = ref('');
const accountKeyword = ref('');
const currentName = ref('');
const premisesList = ref([]);
const dialogDelVisible = ref(false);
const modelValue = ref(false);

const tableRouteLoading = ref(false);
const tablePremisesLoading = ref(false);
const tableNoPremisesLoading = ref(false);
const checkedAccount = ref([]);
const routePremisesSelection = ref([]);
const dialogRouteVisible = ref(false);
const btnLoading = ref(false);
const tableRouteColumns = [
    { label: '序号', key: 'index', render: true, prop: { minWidth: '100px' } },
    { label: '路线名称', key: 'name', render: true, prop: { minWidth: '240px' } },
    { label: '备注', key: 'remark', prop: { minWidth: '240px' } },
    { label: '操作', key: 'action', render: true, prop: { fixed: 'right', minWidth: '180px' } },
];
const tableSetRouteColumns = [
    { label: '序号', key: 'index', render: true, prop: { minWidth: '100px' } },
    { label: '项目名称', key: 'name', prop: { minWidth: '200px' } },
    { label: '物业类型', key: 'type', render: true, prop: { minWidth: '120px' } },
    { label: '详细地址', key: 'address', prop: { minWidth: '240px' } },
    { label: '操作', key: 'action', render: true, prop: { fixed: 'right', minWidth: '120px' } },
];
const tablePremisesColumns = [
    { label: '序号', key: 'index', render: true, prop: { minWidth: '100px' } },
    { label: '项目名称', key: 'name', prop: { minWidth: '220px' } },
    { label: '物业类型', key: 'type', render: true, prop: { minWidth: '120px' } },
    { label: '详细地址', key: 'address', prop: { minWidth: '300px' } },
];
const handleClose = () => {
    dialogVisible.value = false;
};
const handleRouteClose = () => {
    dialogRouteVisible.value = false;
};
const handleAllocateClose = () => {
    isAllocateDialog.value = false;
};
const handlePremisesChange = (val) => {
    premisesList.value = val;
};
const onRouteBatchRemove = async () => {
    let company: any = { company: formData.company };
    let premisesIds = routePremisesSelection.value.map((item) => item.id).join(',');
    await removePremisesFromRoute(premisesIds, company);
    routePremisesSelection.value = [];
    findPremisesByRoute();
    getNotAssociatePremises();
};
const onRemovePremises = async (row: any) => {
    let company: any = { company: formData.company };
    await removePremisesFromRoute(row.id, company);
    findPremisesByRoute();
    getNotAssociatePremises();
};
const onRouteChange = async () => {
    let premisesIds = routePremisesSelection.value.map((item) => item.id).join(',');
    let params = { premisesIds, routeId: changeRouteId.value, company: formData.company };
    btnLoading.value = true;
    try {
        await changeRouteOfPremises(params);
    } finally {
        btnLoading.value = false;
    }

    findPremisesByRoute();
    dialogRouteVisible.value = false;
};
const onAddPremises = async () => {
    let premisesIds = premisesList.value.map((item) => item.id).join(',');
    if (!currentRouteId.value) {
        ElMessage.error('请选择分配路线');
        return false;
    }
    let params = { premisesIds, routeId: currentRouteId.value, company: formData.company };
    await addPremisesToRoute(params);
    premisesList.value = [];
    findPremisesByRoute();
    getNotAssociatePremises();
};
const getRoute = async () => {
    tableRouteLoading.value = true;
    tableDataRouteList.value = await getRouteList(formData);
    tableRouteLoading.value = false;
};
const getNotAssociatePremises = async () => {
    tableNoPremisesLoading.value = true;
    NotAssociatePremisesList.value = await findNotAssociatePremises({ company: userGroup.value.groupCode });
    tableNoPremisesLoading.value = false;
};
// 多选
const handleSeletionChange = (val) => {
    multipleRouteSelection.value = val;
};
const handleRouteChange = (val) => {
    routePremisesSelection.value = val;
};
const addRoute = () => {
    addForm.id = '';
    addForm.name = '';
    addForm.remark = '';
    dialogVisible.value = true;
};
const onAddRoute = async () => {
    await validateForm(addFormRef.value);
    btnLoading.value = true;
    try {
        if (!addForm.id) {
            await saveRoute(addForm);
        } else {
            await updateRoute(addForm);
        }
    } finally {
        btnLoading.value = false;
    }

    dialogVisible.value = false;
    getRoute();
};
const onEdit = (row: any) => {
    Object.assign(addForm, row);
    dialogVisible.value = true;
};
const rowClick = (row: any) => {
    currentRouteId.value = row.id;
};
const onExportRoute = async () => {
    let ids = multipleRouteSelection.value.map((item: any) => item.id).join(',');
    exportLoading.value = true;
    const { file, fileName } = await exportRouteList({ ids, ...formData });
    exportFormBlob(file, fileName);
    exportLoading.value = false;
};
const onDelete = async (row: object) => {
    currentId.value = row.id;
    dialogDelVisible.value = true;
};
const confirmHanle = async () => {
    await deleteRoute({ id: currentId.value, company: formData.company });
    dialogDelVisible.value = false;
    ElMessage.success('删除成功');
    getRoute();
};
const getOnAllocateData = async () => {
    checkedAccount.value = [];
    dataNotAllotAccount.value = await getNotAllotAccountList({
        routeId: currentId.value,
        company: formData.company,
        accountKeyword: '',
        routeName: currentName.value,
    });
    dataAllotAccount.value = await getAllotAccountList({ id: currentId.value });
};
const onAllocate = async (row: object) => {
    isAllocateDialog.value = true;
    currentId.value = row.id;
    currentName.value = row.name;
    getOnAllocateData();
};
const getRoutePremises = async (row: object) => {
    currentRouteId.value = row.id;
    currentRouteName.value = row.name;
    findPremisesByRoute();
    modelValue.value = true;
};
const findPremisesByRoute = async () => {
    let company: any = { company: formData.company };
    tablePremisesLoading.value = true;
    tablePremisesData.value = await findPremisesByRouteId(currentRouteId.value, company);
    tablePremisesLoading.value = false;
};
const onDelAccount = async (index: number) => {
    dataAllotAccount.value.splice(index, 1);
    let params = {
        company: formData.company,
        routeId: currentId.value,
        accountList: dataAllotAccount.value,
        routeName: currentName.value,
    };
    await allotAccount(params);
    getOnAllocateData();
};
const onAccountAallot = async () => {
    let params = {
        company: formData.company,
        routeId: currentId.value,
        accountList: checkedAccount.value,
        routeName: currentName.value,
    };
    btnLoading.value = true;
    try {
        await allotAccount(params);
    } finally {
        btnLoading.value = false;
    }

    getOnAllocateData();
    ElMessage.success('分配成功');
};
const onSearchAccount = async () => {
    dataNotAllotAccount.value = await getNotAllotAccountList({
        routeId: currentId.value,
        company: formData.company,
        accountKeyword: accountKeyword.value,
    });
};
onMounted(async () => {
    grouplist.value = [{ label: userGroup.value.groupName, value: userGroup.value.groupCode }];
    formData.company = userGroup.value.groupCode;
    addForm.company = userGroup.value.groupCode;
    getRoute();
    getNotAssociatePremises();
});
</script>

<style lang="scss" scoped>
#xc-table {
    height: 100%;
}
h3 {
    margin-bottom: 20px;
}
.itemAccount {
    display: inline-block;
    padding: 2px 6px;
    border: 1px solid #ddd;
    border-radius: 2px;
    margin: 5px;
}
.row-actions__more {
    cursor: pointer;
    width: 1em;
    height: 1em;
    margin: 0 20px;
}
.el-dropdown-link {
    display: inline-block;
    margin-top: 10px;
}
::v-deep.pinmei-form {
    .label {
        margin-top: 2px;
    }
    .formname .el-input__inner {
        padding-left: 32px !important;
    }
}
</style>
